package {
	import flash.display.*;
	import flash.events.Event;
	import flash.text.*;
	
	[SWF(width="1000", height="600", frameRate="30", backgroundColor="#aaaaaa")]
	public class WBSBuilder extends Sprite
	{
		private var rootNode:WBSnode = new WBSnode();
		private var myWBSConnector:WBS;
		
		private var field_wbs_id:TextField = new TextField();
		
		public function WBSBuilder()
		{
		 	myWBSConnector = new WBS();
			myWBSConnector.addEventListener("nodesLoaded",processNodes);
			
		}
		
		private function processNodes(e:Event):void{
			trace(myWBSConnector.nodes[0].node_id);
			rootNode.name = "root";
			/* rootNode.graphics.beginFill(0x000000);
			rootNode.graphics.drawRoundRect(0,0,50,22,5,5); */
			rootNode.x = stage.stageWidth/2-rootNode.width/2
			rootNode.y = 40;
			addChild(rootNode);
			buildTree(myWBSConnector.nodes[0],null,0)
		}
		
		private function buildTree(nodeData:Object, parent:WBSnode, index:int):void{
			trace("node_id: " + nodeData.node_id + " node index: " + index + " parent.name: " + parent + " nodeData.name: " + nodeData.name);
				var node:WBSnode;
				/*Vincent's code starts here*/
				//var wbs_id:TextField;
				/*Vincent's code ends here*/
			if(parent == null){
				node = rootNode;
			}else{
				node = new WBSnode(nodeData.name);
				/*Vincent's code starts here*/
				//var wbs_id:TextField;
				
				/*Vincent's code ends here*/
				/* node.graphics.beginFill(0xffffff*Math.random());
				node.graphics.drawRoundRect(stage.stageWidth/2 - node.width/2,stage.stageHeight/2 - node.height/2,50,22,5,5); */
				parent.addNode(node);
				
				if(parent == rootNode){
					//Children of the root should be horizontal
					trace("parent is root");
					node.y = 40;
					if(index == 0){
						node.x = stage.stageWidth/2 - this.width/2;
					}else{
						trace("top nodes: " + rootNode.getChildAt(index-1).width);
						node.x = rootNode.getChildAt(index-1).width+10;
					}
				}/* else{
					node.x = 10;
					if(index == 0){
						node.y = 27;
					}else{
						node.y = (parent.getChildAt(index-1).y+parent.getChildAt(index-1).height)+5;
					}
					
				} */
			}
			
			var tempIndex:int = 0;
			for(var i:int=0;i<myWBSConnector.nodes.length;i++){
				if(myWBSConnector.nodes[i].parent_id == nodeData.node_id){
					buildTree(myWBSConnector.nodes[i],node,tempIndex);
					
					field_wbs_id.text = "1.0" + tempIndex;
					//node.addChild(field_wbs_id);
					tempIndex++;
					
					//trace("id: " + id + " tempIndex: " + tempIndex);
				}
			}
			
		}
	}
}
